// pages/searchResult/searchResult.js
// pages/search/search.js
import request from '../../utils/request'
let isSend = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    songList: [],//歌曲数据
    searchContent: '',//输入的搜索内容
    searchList: [],//模糊匹配结果
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //获取歌曲数据
    this.getSongData(options.keywords)
  },
  //获取歌曲数据
  async getSongData(keywords,offset=0) {
    //获取搜索到的歌曲数据
    let songListData = await request('/search',{keywords,offset});
    this.setData({
      searchContent: keywords,
      songList: songListData.result.songs
    })
  },
  //搜索框内容改变的回调
  handleInputChange() {
    //函数节流
    if(isSend){
      return
    }
    isSend = true;
    this.getSearchList()
    setTimeout(() => {
      isSend = false
    }, 30);
  },
  //获取搜索建议数据
  async getSearchList(){
    if(!this.data.searchContent){
      return
    }
    //发请求获取数据
    let searchListData = await request('/search/suggest', { keywords: this.data.searchContent.trim(), type: 'mobile' })
    this.setData({
      searchList: searchListData.result.allMatch
    })
  },
  //点击搜索触发的回调
  handleConfirm(){
    //清空当前结果
    this.setData({
      searchList:[]
    })
    //添加历史记录
    let {searchContent} = this.data
    let historyList = wx.getStorageSync('searchHistory')
    if(searchContent && (historyList.indexOf(searchContent)===-1)){
      historyList.unshift(searchContent)
    }
    wx.setStorageSync('searchHistory', historyList)
    this.getSongData(searchContent)
  },
  //点击清空搜索内容
  clearSearchContent(){
    this.setData({
      searchContent:'',
      searchList:[]
    })
  },
  //点击取消搜索
  cancelSearch(){
    this.setData({
      searchList:[],
    })
  },
  //跳转至播放歌曲页面
  toSongDetail(event){
    let songId = event.currentTarget.id;
    wx.navigateTo({
      url: '/songPackage/pages/songDetail/songDetail?ids='+songId,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})